package com.itheima.api.array.demo01;

public class ArrayBinarySearchDemo {

    public static void main(String[] args) {

        int[] arr = {1,2,3,4,5,6,7,8,9};
        int binarySearch = binarySearch(arr, 2);
        System.out.println(binarySearch);
    }

    public static int binarySearch(int[] arr, int key){

        int minIndex = 0;
        int maxIndex = arr.length - 1;
        int midIndex = (minIndex + maxIndex) / 2;

        while (minIndex <= maxIndex) {
            if (arr[midIndex] == key) {
                return midIndex;
            } else if (arr[midIndex] > key) {
                maxIndex = midIndex - 1;
            } else {
                minIndex = midIndex + 1;
            }

            midIndex = (minIndex + maxIndex) / 2;
        }
        return -1;
    }
}
